<template>
  <div id="container">
    <div>
      <div id="countdown" v-show="countdown.flag">
        {{countdown.number}}
      </div>
      <div id="win" v-show="overFlag&&showRanking==false" style="margin-top:80px;">
        <div v-if="userTop!=null&&userTop.score>=rightScore*10">
          <div style="font-size: 110px;text-align: center;font-weight: bold;" >
            {{userTop!=null?userTop.nickName:''}} 攻坚成功！
          </div>
          <div><img src="@/assets/images/5040d0c12b0cd2ab391d1a4f041779d1.gif" width="1200" height="1200" /></div>
        </div>
        <div v-else  style="font-size: 100px;text-align: center;font-weight: bold;margin-bottom:80px;">本轮比赛结束，请继续加油！</div>
        <div style="text-align: center;"><el-button type="primary" @click="showRank">查看排名</el-button></div>
      </div>
      <div id="header-top">
        <img src="../../assets/images/logo-long.png" width="32%"/>
        <div v-if="!startFlag&&currentIndex<maxIndex">
          <el-button type="primary" @click="ready" style="width:300px;height:50px;">开始比赛</el-button>
        </div>
        <div v-else-if="startFlag&&userTop!=null">
          <div style="display: flex;">
            <div style="font-size: 80px;font-weight: bold;margin-right: 450px; ">当前实时第一名({{userTop.nickName}}) </div>
            <div style="font-size: 120px;font-weight: bold;line-height: 90px;" v-if="userTop.score!=null&&userTop.score!=0">{{userTop.score==null?'0':userTop.score/3}}</div>
            <div style="font-size: 80px;">/10</div>
          </div>
          <div style="margin-top:10px;">
            <el-progress :stroke-width="50" :percentage="userTop.score/30*100" color="#fa9761" define-back-color="#e5e5e5" :show-text="false"></el-progress>
          </div>
        </div>
        <div style="font-size: 130px;color:yellow;font-weight: bold;" v-show="startFlag&&answerCountDown.flag">
          {{answerCountDown.text}}
        </div>
      </div>
      <div style="padding:0px 10%;">
        <div style="display: flex">
          <div style="font-size:100px;font-weight: bold;text-align: center;margin-right:100px;width:7%;margin-top:5%;writing-mode: vertical-rl;transform: rotate(0deg);" v-show="showRanking">
            本轮比赛得分
          </div>
          <div v-if="showRanking" style="width:80%;margin-top: 50px;">
            <div>
              <el-table :data="doorRanks" style="width: 100%;" :cell-class-name="tableRowClassName"
                        :header-cell-style="{'background-color': '#cd1c26','color':'#fff','font-weight':'bolder'}"
                        id="rank-table">
                <el-table-column prop="rank" align="center" label="排名" min-width="25%"></el-table-column>
                <el-table-column prop="nickName" align="center" label="台号" min-width="25%">
                  <template scope="scope">
                    <div style="color: rgb(205,28,38);">{{scope.row.nickName}}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="score" align="center" label="分数" min-width="25%">
                  <template scope="scope">
                    <div style="color: rgb(205,28,38);">{{scope.row.score}}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="rightCount" align="center"  label="答对题数" min-width="25%"></el-table-column>


              </el-table>
            </div>
          </div>
        </div>
        <el-row :gutter="160" v-if="!overFlag">
          <el-col :span="8" v-for="(user,index) in userList">
            <div class="question">
              <div class="question-header">
                <div class="question-top">
                  <div class="number">{{index+1}}</div>
                  <!--                  <div class="nickname">第{{index+1}}组参赛选手（{{user.nickName}}）</div>-->
                  <div class="nickname">{{user.nickName}}</div>

                </div>
                <div class="question-score">{{user.score/3}}/10</div>
              </div>
              <div class="process">
<!--                <el-progress :stroke-width="10" :percentage="user.score/30*100" :show-text="false" color="#ed352f" define-back-color="#e5e5e5" ></el-progress>-->
                <el-progress :stroke-width="10" :percentage="user.questionIndex/maxQuestionCount*100" :show-text="false" color="#ed352f" define-back-color="#e5e5e5" ></el-progress>
              </div>
              <div  v-if="startFlag&&user.questionIndex<maxQuestionCount">
                <div class="question-list">
                  {{user.questionIndex+1}}.{{questionList[user.questionIndex].questionName}}
                </div>
                <el-row>
                  <el-col :span="12" v-for="question in ['a','b','c','d','e','f']" v-if="['SINGLE','MULTIPLE','SINGLE_OR_MULTIPLE'].includes(questionList[user.questionIndex].questionType)">
                    <div :class="optionChecked(user,question.toUpperCase())" v-if="questionList[user.questionIndex][question]!=null&&questionList[user.questionIndex][question]!=''">
                      {{question.toUpperCase()}}：{{questionList[user.questionIndex][question]}}
                    </div>
                  </el-col>
                  <el-col :span="12" v-for="question in ['a','b']" v-if="questionList[user.questionIndex].questionType=='JUDGE'">
                    <div :class="optionChecked(user,question.toUpperCase())">{{question.toUpperCase()}}：{{question=='a'?'正确':'错误'}}</div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import websocket from "@/utils/webSocket";
import {Howl, Howler} from 'howler';
// import io from "socket.io-client";
export default {
  name: "index",
  data(){
    return {
      answerCountDown:{
        flag:true,
        second:0,
        text:null
      },
      socketUrl:"ws://"+process.env.VUE_APP_SOCKET_URL+"/websocket/"+this.$route.query.zoomId+"/0",
      socket:null,
      userList:[],
      doorRanks:[],
      doorRankList:[],
      questionList:[],
      startFlag:false,
      beforeStartFlag:false,
      overFlag:false,
      currentIndex:0,
      questionAllList:[],
      maxIndex:3,
      maxQuestionCount:20,
      rightScore:3,//答对一题加的分数
      countdown:{
        flag:false,
        number:4,
        timer:null
      },
      userTop:null,
      showRanking:false,
      // bgAudio:null,
      startAudio:null,
      overAudio:null,
      failAudio:null,
      chineseNumber:['一','一','二','三']
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.zoom();
      window.addEventListener('resize', this.zoom, false);
      this.init();
      this.createSocket();
    })
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.closeSocket();
    }
  },
  methods:{
    init(){
      const that=this;
      this.startAudio = new Howl({
        src: ['/video/63c0ecfebcf37476.mp3']
      });
      this.overAudio = new Howl({
        src: ['/video/5d819f82bece841811.mp3']
      });
      // this.failAudio = new Howl({
      //   src: ['/video/5c89164b99c5436435.mp3']
      // });

      this.startAudio.on('load', function() {
        console.log('音频已加载完成1');
      });
      this.overAudio.on('load', function() {
        console.log('音频已加载完成2');
      });
      // this.failAudio.on('load', function() {
      //   console.log('音频已加载完成3');
      // });
      this.startAudio.on('play', function() {
        that.countdownStart();
        // setTimeout(function(){
        //   that.countdownStart();
        // },5000)
      });
    },
    countdownStart(){
      const that=this;
      this.countdown.flag=true;
      if(this.countdown.number<=1){
        this.countdown.flag=false;
        this.resetFlag();
        this.currentIndex++;
      }else{
        this.countdown.number--;
        setTimeout(that.countdownStart,1000);
      }
    },
    answerCountDownStart(){
      const that=this;
      // this.answerCountDown.second=180;
      if(this.answerCountDown.second<=0){
        this.socket.sendMsg({
          type: "OVERTIME",
          data: {
            index: this.currentIndex
          }
        })
      }else{
        this.answerCountDown.second--;
        this.answerCountDown.text=parseInt(this.answerCountDown.second/60)+":"+String(parseInt(this.answerCountDown.second%60)).padStart(2, '0');
        if(this.answerCountDown.flag&&this.startFlag){
          setTimeout(that.answerCountDownStart,1000);
        }
      }

    },
    playStartVideo(){
      this.startAudio.play();
      // const audio = new Audio('/video/63c0ecfebcf37476.mp3');
      // this.playOverVideo();
      // this.startAudio.play()
      //   .then(() => {
      //     // 音频成功播放
      //   })
      //   .catch(err => {
      //     console.error(err);
      //     // 处理播放错误
      //   });
    },
    playOverVideo(){
      if(this.userTop!=null&&this.userTop.score>=this.rightScore*10){
        this.overAudio.play();
      }else{
        // this.failAudio.play();
      }
      // let that=this;
      // setTimeout(function(){
      //   that.startAudio.load();
      //   that.overAudio.load();
      //   that.failAudio.load();
      // },8000)


      // this.bgAudio.play()
      //   .then(() => {
      //     // 音频成功播放
      //   })
      //   .catch(err => {
      //     console.error(err);
      //     // 处理播放错误
      //   });
    },
    // stopOverVideo(){
    //   if(this.bgAudio!=null){
    //     this.bgAudio.pause();
    //   }
    // },
    resetFlag(){
      if(this.startFlag==false){
        this.startFlag=true;
      }
      this.number=4;
      this.answerCountDown.text=null;
      this.answerCountDown.second=181;
      this.answerCountDown.flag = true;
      this.answerCountDownStart();
      this.userTop=null;
    },

    ready(){
      this.showRanking=false;
      this.beforeStartFlag=true;
      if(this.overFlag){
        this.overFlag=false;
      }
      for(let i in this.userList){
        this.userList[i].score=0;
        this.userList[i].questionIndex=0;
      }
      // this.stopOverVideo();
      this.socket.sendMsg({
        type: "READY",
        data: {
          index: this.currentIndex+1
        }
      })
    },
    createSocket(){
      const that=this;
      this.socket=new websocket(this.socketUrl,{
        onmessage(data){
          switch(data.type){
            case "ZOOMUSERLIST":
              if(!that.beforeStartFlag){
                if(data.data!=null){
                  that.userList=data.data;
                }
              }
              //找出第一名的分数
              if(that.beforeStartFlag){
                // that.userList=data.data;
                let score=0;
                let user={};
                for(let i in that.userList){
                  if(that.userList[i].score>score){
                    user=that.userList[i];
                    score=that.userList[i].score;
                  }
                }
                that.userTop=user;
              }
              break;
            case "ANSWER":
              const answer=data.data;
              for(let i in that.userList){
                if(that.userList[i].userId==answer.userId){
                    that.userList[i].answer=answer.answer;
                    that.userList[i].result=answer.result;
                    if(answer.result){
                      that.userList[i].score+=that.rightScore;
                    }
                    that.$forceUpdate();
                    setTimeout(function(){
                      that.userList[i].answer='';
                      that.userList[i].result=null;
                      that.userList[i].questionIndex++;
                      // console.log(that.userList[i].questionIndex);
                    },1000)
                  break;
                }
              }
              break;
            case "START":
              that.countdown.number=4;
              // that.countdownStart();
              that.playStartVideo();
              if(data.data!=null&&data.data!=''&&data.data.length!=0){
                that.questionAllList=data.data;
              }
              // that.currentIndex=data.index;
              that.questionList=that.questionAllList.slice(that.maxQuestionCount * that.currentIndex, that
                .maxQuestionCount * (that.currentIndex+1));
              that.questionIndex=0;
              break;
            case "OVER_ANSWER":
              that.overAnswer(data);
              break;
            case "OVERTIMECANCEL":
              that.answerCountDown.flag=false;
              break;
          }
        }
      });
    },
    overAnswer(data){
      this.playOverVideo();
      this.startFlag=false;
      this.overFlag=true;
      this.beforeStartFlag=false;
      this.doorRanks=data.data.doorRanks;
      if(this.currentIndex>=this.maxIndex){
        this.doorRankList=data.data.doorRankList;
      }
    },
    showRank(){
      this.showRanking=true;
    },
    optionChecked(user,answer){
      if(['JUDGE'].includes(this.questionList[user.questionIndex].questionType)){
        if(user.answer==null||user.answer==''){
          return 'option';
        }else if(user.answer==answer){
          if(user.result==true){
            return 'option-right';
          }else{
            return 'option-error shakeHead';
          }
        }else{
          return 'option';
        }
      }else{
        if(user.answer==null||user.answer==''){
          return 'option';
        }else if(user.answer.includes(answer)){
          if(this.questionList[user.questionIndex].answer.includes(answer)){
            return 'option-right';
          }else{
            return 'option-error shakeHead';
          }
        }else if(this.questionList[user.questionIndex].answer.includes(answer)){
          return 'option-right shakeHead';
        }else{
          return 'option';
        }
      }

    },
    zoom(){
      let x = document.body.clientWidth / 4726 // 固定值
      let y = document.body.clientHeight / 1969 // 固定值
      let scale=Math.min(x,y);
      console.log(scale);
      let domBody = document.getElementById('container');
      domBody.style.transform= "scale("+scale+", "+scale+")  translate(-50%, -50%)"
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex %2==0) {
        return 'table-odd';
      } else {
        return 'table-even'
      }
    }
  }
}
</script>

<style scoped>
@import "../../assets/styles/dataV2.css";
</style>
